from typing import Optional
from apps.db import Student
from pydantic import BaseModel
from fastapi import APIRouter

router = APIRouter(
    prefix="/students",
    tags=["students"],
)


class StudentModel(BaseModel):
    name: str
    age: int
    gender: Optional[str] = None


result = {'code': 10000, 'msg': 'ok'}


@router.get("/", tags=['students'], summary="查询所有学生", description="这是额外的描述信息, 如果不写, 默认使用文档注释")
async def root():
    """api:查询所有学生"""
    data = []
    for student in Student.select().dicts():
        data.append(student)
    result['data'] = data
    return result


@router.post("/", summary="添加一个学生", description='添加一个学生')
async def student_add(student: StudentModel):
    """
    添加一个学生
    :param student: 学生对象
    :return: json信息
    """
    Student.create(name=student.name, age=student.age, gender=student.gender)
    return result


@router.delete("/{id}", summary="根据id删除学生")
async def student_delete(id: int):
    """api: 根据id删除"""
    Student.delete().where(Student.id == id).execute()
    return {"code": 10000, "msg": "ok"}


@router.get("/{id}", summary="根据id获取学生信息")
async def student_find(id: int):
    """api: 根据id查找"""
    data = []
    for student in Student.select().where(Student.id == id).dicts():
        data.append(student)
    result['data'] = data
    return result


@router.put("/{id}", summary="根据id更新学生信息")
async def student_find(student: StudentModel, id: int):
    """api: 根据id查找"""
    Student.update(name=student.name, age=student.age, gender=student.gender).where(Student.id == id).execute()
    return result
